<template>
  <starGenView :title="lang.title">
    <Row>
      <Col flex="0 1 600px" class="textureLib-left">
        <div>
          <cfg-table
            ref="table"
            :columns="columns"
            :expandColumns="expandColumns"
            :data="collectionObject.records"
            :config="tableConfig"
            :pageSizeOpts="pageSizeOpts"
            :pageNavigation="pageNavigation"
            :queryFormItem="queryFormItem"
            :collapseFormItem="collapseFormItem"
            :additionalAction="additionalAction"
            :actionButtons="actionButtonsCalc"
            @loadPage="loadPage"
            @handleClick="handleClick"
            @handleDbClick="(row, index) => $emit('handleDbClick', row, index)"
            @handleSelect="(selection, row) => $emit('handleSelect', selection, row)"
            @handleSelectCancel="(selection, row) => $emit('handleSelectCancel', selection, row)"
            @handleCreate="handleCreate"
            @handleDetail="handleDetail"
            @handleEdit="handleEdit"
            @handleDelete="handleDelete"
            @handleDeleteMultiple="handleDeleteMultiple"
            @handleSearch="handleSearch"
            @handleReset="handleReset"
          />
          <cfgCrudAddModal
            v-show="modelDrawer.status==='new'"
            v-bind="modalConfig"
            :classObject="classObject"
            :collectionObject="collectionObject"
            :drawer="modelDrawer"
            :fields="modalFormItem"
            @submit="handleNewAddSubmit"
          />
          <cfgCrudModal
            v-show="modelDrawer.status!=='new'"
            v-bind="modalConfig"
            :classObject="classObject"
            :collectionObject="collectionObject"
            :modelList="modelList"
            :drawer="modelDrawer"
            :fields="modalFormItem"
            @submit="handleEditSubmit"
          />
          <!-- <cfgModal
                v-bind="modalConfig"
                :data="classObject.record"
                :modelList="modelList"
                :drawer="modelDrawer"
                :fields="modalFormItem"
                @submit="handleOk"
                /> -->
            <FieldUpload :config="uploadConfig" @change="uploadChange" class="ivu-mt"/>
        </div>
      </Col>
      <Col flex="1" class="textureLib-right">
        <Card :class="['previewwp flex', fullscreen ? 'fullscreen' : '']" dis-hover>
          <div class="flex-middle" slot="title">
            <span class="ivu-mr">{{ lang.previewPictrue }}</span>
            <Button type="text" icon="md-qr-scanner" @click="onFullScreen"></Button>
          </div>
          <div class="imgwp flex1" :style="{backgroundImage: `url(${detailPicture})`}">
            <Spin v-show="loading" fix></Spin>
            <!-- <img src="dat:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAAhGVYSWZNTQAqAAAACAAFARIAAwAAAAEAAQAAARoABQAAAAEAAABKARsABQAAAAEAAABSASgAAwAAAAEAAgAAh2kABAAAAAEAAABaAAAAAAAAAJAAAAABAAAAkAAAAAEAA6ABAAMAAAABAAEAAKACAAQAAAABAAAACqADAAQAAAABAAAACgAAAAApQFlgAAAACXBIWXMAABYlAAAWJQFJUiTwAAABWWlUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iWE1QIENvcmUgNi4wLjAiPgogICA8cmRmOlJERiB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiPgogICAgICA8cmRmOkRlc2NyaXB0aW9uIHJkZjphYm91dD0iIgogICAgICAgICAgICB4bWxuczp0aWZmPSJodHRwOi8vbnMuYWRvYmUuY29tL3RpZmYvMS4wLyI+CiAgICAgICAgIDx0aWZmOk9yaWVudGF0aW9uPjE8L3RpZmY6T3JpZW50YXRpb24+CiAgICAgIDwvcmRmOkRlc2NyaXB0aW9uPgogICA8L3JkZjpSREY+CjwveDp4bXBtZXRhPgoZXuEHAAABcklEQVQYGS2QMUscURSFz333zZvZdWZcI2TFZZu0QsRCgo0I9sEiJP8gncJW6h8wpBKyVfp0Fsk/SCMpttCIgoJuYQILQYlml2V25s17N7MhF75TnHvhHC7h/0j59RWEdiB+WSAgUmfwvkvh5tH0hKYicnwARPtABngHKK5cUxFU2PdEL/bo/qa7Nb+Yfh7dD6RkcjBPmHWEwGaOnWgz10Ax+PFa88VxRy7HYAmKMIlDX49g1TTFa5eYEsNC24Hb1mObruQLbZRFbvwY0MIwRkGYUZgWT4IcQfNiWT/+BtXmnkLMI2zDVp0UfClg66H6fah2jklsoH3v9iS6/rWu2mkhxoV/UkbStGjMWBT1yNki1g9DOlOuhkNKIzzkxFcj5N/rRkYRSwKXz8dQCzMZWpJ94I+9/tXqy+fB+VK8MVqKNGaJLsdMLUU6SQxld8N36dpR998fq2I4+PZ26xn7Tgis3JWE25/5aUr+cPfNpy/T/V9VyJWbmPHWawAAAABJRU5ErkJggg==" alt=""> -->
            <p class="empty ivu-mt" v-if="rowIndex !== null && !loading && !detailPicture">{{lang.emptyMessage}}</p>
          </div>
        </Card>
      </Col>
    </Row>
  </starGenView>
</template>

<script>
import modelMixin from 'public/components/configComp/mixins/modelMixin';
import FieldUpload from 'public/components/basic/fieldUpload.vue';
import Setting from '@/setting.js'
import axios from 'axios'

export default {
    components: { FieldUpload },
    mixins: [modelMixin],
    data() {
        return {
            modelName: 'mesh',
            deleteById: true,
            tableConfig: {
              //   highlightRow: true,
                labelWidth: 68,
                actionDetail: false,
                actionOption: {
                    width: 120,
                },
                additionalAction: {  // 附加操作的配置，以及button列表
                    show: true,
                    width: 180,
                    buttons: [
                        {
                            title: { 'zh-CN': '下载Base64', 'en-US': 'download picture' }, color: 'green',
                            eventName: 'actionDownLoadBase64'
                        },
                        {
                            title: { 'zh-CN': '下载', 'en-US': 'download picture' }, color: 'green',
                            eventName: 'actionDownLoad'
                        },
                    ]
                }
            },
            modalConfig: {
                hasFeatures: false,
                labelWidth: 90,
            },
            fullscreen: false,
            rowIndex: null,
            detailPicture: '',
            loading: false,
            uploadConfig: {
                maxSize: 500*1024,
                format: ['jpg', 'jpeg', 'png', 'dmg', 'zip', 'fbx'],
                action: Setting.apiBaseURL + '/star5.0/mesh/uploadFile',
                data: {id: 1},
            },
        }
    },
    methods: {
        uploadChange(val) {
            // console.log("file: index.vue:119  uploadChange  val:", val)
        },
        handleClick(row, index) {
            let tmpPicture = ''
            this.loading = true
            this.detailPicture = tmpPicture
            this.rowIndex = index
            this.classObject.api.query({condition: `id=${row.id}`}).then(res => {
                if (res && res.length && res[0].fileName) {
                    tmpPicture = Setting.apiBaseURL + res[0].fileName.replace(/^./, '/star5.0')
                    console.log("file: index.vue:139  this.classObject.api.query  tmpPicture:", res[0].fileName,tmpPicture)
                }
                this.detailPicture = tmpPicture
                this.loading = false
            }).catch(err=> {
                this.detailPicture = tmpPicture
                this.loading = false
            })
        },
        onFullScreen() {
            this.fullscreen = !this.fullscreen
        },
        async actionDownLoadBase64(row, index) {
            this.classObject.setRecord(row)
            let flag
            // flag = await this.classObject.downloadFileBase64ById()
            flag = await this.classObject.downloadFileBase64ByName()

            if (flag) {
                this.detailPicture = 'data:image/png;base64,' + this.classObject.fileBase64
            }
        },
        async actionDownLoad(row, index) {
            this.classObject.setRecord(row)
            let flag
            // flag = await this.classObject.downloadFileById()
            // flag = await this.classObject.downloadFileByName()
            // this.blobToImg(this.classObject.file, 'x11.png')
            // return 

            let detailPicture = Setting.apiBaseURL + row.fileName.replace(/^./, '/star5.0')
            this.downloadImage(detailPicture, 'x1.png')
        },
        downloadImage(imageUrl, name) {
            axios.get(imageUrl, {responseType: 'blob'}).then((res) => {
                this.blobToImg(res.data, name)
            });
        },
        blobToImg(blob, name) {
            const downloadUrl = window.URL.createObjectURL(new Blob([blob]));
            console.log("file: index.vue:181  blobToImg", new Blob([blob]))
            const link = document.createElement('a');
            link.href = downloadUrl;
            link.setAttribute('download', name);
            document.body.appendChild(link);
            link.click();
            link.remove();
        }
    },
    computed: {
        // table的columns配置
        columns() {
            return [
                {
                    key: 'type',
                    title: {
                        'zh-CN': '所属类型',
                        'en-US': 'type'
                    }[this.G_Locale],
                    minWidth: 100,
                    align: 'center',
                    show: true
                },
                {
                    key: 'name',
                    title: {
                        'zh-CN': '名称',
                        'en-US': 'name'
                    }[this.G_Locale],
                    minWidth: 100,
                    align: 'center',
                    show: true
                },
                // {
                //     key: 'createTime',
                //     title: {
                //         'zh-CN': '创建时间',
                //         'en-US': 'create time'
                //     }[this.G_Locale],
                //     width: 180,
                //     align: 'center',
                //     show: true,
                // },
                // {
                //     key: 'updateTime',
                //     title: {
                //         'zh-CN': '更新时间',
                //         'en-US': 'update time'
                //     }[this.G_Locale],
                //     width: 180,
                //     align: 'center',
                //     show: true,
                // },
            ]
        },
        // 新增、查看、编辑弹窗，表单展示的字段
        modalFormItem() {
            return [
                {
                    key: 'type',
                    title: this.$t(`model.type`),
                    config: { type: 'text', clearable: true, },
                    // editConfig: { disabled: true },
                    rules: [
                        { required: true, trigger: 'blur',
                            message: this.$t(`model.type`)+this.$t(`global.notEmpty`)
                        }
                    ]
                },
                {
                    key: 'name',
                    title: { 'zh-CN': '名称', 'en-US': 'name' }[this.G_Locale],
                    config: {
                        type: 'text',
                        maxlength: 50,
                        clearable: true,
                        placeholder: {
                            'zh-CN': '请输入名称',
                            'en-US': 'please input name'
                        }[this.G_Locale]
                    },
                    // editConfig: { disabled: true },
                    rules: [
                        { required: true, trigger: 'blur',
                            message: { 'zh-CN': '名称不能为空', 'en-US': 'The name cannot be empty' }[this.G_Locale]
                        }
                    ]
                },
                {
                    key: 'picture',
                    title: {
                        'zh-CN': '图片',
                        'en-US': 'picture'
                    }[this.G_Locale],
                    span: 24,
                    config: {
                        type: 'upload',
                        maxSize: 50*1024,
                        format: ['jpg', 'jpeg', 'png', 'dmg'],
                        clearable: true,
                        placeholder: {
                            'zh-CN': '请上传图片',
                            'en-US': 'please upload picture'
                        }[this.G_Locale],
                    }
                },
            ]
        },
        // 顶部搜索表单，展示的字段
        queryFormItem() {
            return [
                {
                    key: 'type',
                    title: {
                        'zh-CN': '所属类型',
                        'en-US': 'type'
                    }[this.G_Locale],
                    config: { type: 'text', clearable: true },
                    labelWidth: 60,
                },
                {
                    key: 'name',
                    title: {
                        'zh-CN': '名称',
                        'en-US': 'name'
                    }[this.G_Locale],
                    config: { type: 'text', clearable: true, },
                    labelWidth: 60,
                },
            ]
        },
        lang() {
            return {
                'zh-CN': {
                    title: 'meshManage',
                    previewPictrue: '预览图片',
                    emptyMessage: '当前记录没有配置图片',
                  },
                  'en-US': {
                    title: 'meshManage',
                    previewPictrue: 'preview pictrue',
                    emptyMessage: 'There are no configured pictrue for the current record',
                }
            }[this.G_Locale]
        },
    }
}
</script>

<style lang="less" scoped>
/deep/ .cli-content-column {
    height: 100%;
}
.ivu-row {
    height: 100%;
}
.textureLib-left {
    height: 100%;
    margin-right: 8px;
    overflow: hidden auto;
    background-color: #fff;
}
.textureLib-right {
    height: 100%;
    overflow: hidden auto;
    background-color: #fff;
    .previewwp {
        position: relative;
        width: 100%;
        height: 100%;
        flex-direction: column;
        background-color: #fff;
        &.fullscreen {
            position: fixed;
            top: 0;
            bottom: 0;
            left: 0;
            right: 0;
            z-index: 1001;
        }
        /deep/ .ivu-card-head {
            font-size: 18px;
            font-weight: 500;
        }
        /deep/ .ivu-card-body {
            flex: 1;
        }
    }
    .imgwp {
        position: relative;
        height: 100%;
        background-size: contain;
        background-position: center 0;
        background-repeat: no-repeat;
    }
    .empty {
        font-size: 18px;
        font-weight: 500;
        text-align: center;
    }
}
</style>
